# @FileName  : fileLoc.py
# @Time      : 2022/3/5 0005  10:18
# @Author    : LuZhaoHui
# @Software  : PyCharm

import copy
# 档案数字管理-本地板
import json
import sys

from CacheUi import Ui_CacheWindow
from FileUI import Ui_MainWindow
from ImageUI import Ui_ImageWindow
from NameUI import Ui_NameWindow
from tool import *

# IMG_EXT = (".jpg")
XLS_EXT = (".xls", ".xlsx")

ver = '2.25.9.28'

# 2024.4.30
RESERVED_EXT = ('.lst', '.frm', '.split')

PROJECT_DICT1 = {
    # 目录-ProjectPath
    'ProjectPath': '',
    # 分类号 ProjectClassNo
    'ProjectClassNo': '',
    # 工程名称-ProjectName
    'ProjectName': '',
    # 工程地点-ProjectAddr
    'ProjectAddr': '',
    # 建筑面积-ProjectBuildArea
    'ProjectBuildArea': '',
    # 结构类型-ProjectStructType
    # 'ProjectStructType': '',
    # 保管期限-ProjectKeepLimit
    'ProjectKeepLimit': 0,
    # 密级-ProjectSecretDegree
    'ProjectSecretDegree': 0,
    # 移交单位-ProjectHandUnit
    'ProjectHandUnit': '',
    # 建设单位-ProjectBuildUnit
    'ProjectBuildUnit': '',
    # 施工单位-ProjectConstructUnit
    'ProjectConstructUnit': '',
    # 编制单位-ProjectAuthorUnit
    'ProjectAuthorUnit': '',
    # 总卷数-ProjectVolTotal
    'ProjectVolTotal': 1,
    # 文字卷数-ProjectWordVolNums
    'ProjectWordVolNums': 0,
    # 文字张数-ProjectWordFrameNums
    'ProjectWordFrameNums': 0,
    # 图纸卷数-ProjectPicVolNums
    'ProjectPicVolNums': 0,
    # 图纸张数-ProjectPicFrameNums
    'ProjectPicFrameNums': 0,
    # 开工日期-ProjectStartWorkDate
    'ProjectStartWorkDate': nowDateStr(),
    # 竣工日期-ProjectCompleteDate
    'ProjectCompleteDate': nowDateStr(),
    # 进馆日期-ProjectEnterDate
    'ProjectEnterDate': nowDateStr(),
    # 位置坐标X1
    'ProjectLocateX1': 0.0,
    # 位置坐标Y1
    'ProjectLocateY1': 0.0,
    # 位置坐标X2
    'ProjectLocateX2': 0.0,
    # 位置坐标Y2
    'ProjectLocateY2': 0.0,
    # 位置坐标X3
    'ProjectLocateX3': 0.0,
    # 位置坐标Y3
    'ProjectLocateY3': 0.0,
    # 位置坐标X4
    'ProjectLocateX4': 0.0,
    # 位置坐标Y4
    'ProjectLocateY4': 0.0,
    # 存放地址-ProjectStoreAddr
    # 'ProjectStoreAddr': '',
    # 编辑时间-ProjectEditDatetime
    # 'ProjectEditDatetime': nowDateTimeStr(),
    # 编辑人-ProjectEditor
    'ProjectEditor': ''
}

PROJECT_DICT2 = {
    # 目录-VolumePath
    'VolumePath': '',
    # 卷标题-VolumeTitle
    'VolumeTitle': '',
    # 编制单位-VolumeAuthorUnit
    # 'VolumeAuthorUnit': '',
    # 分类号 VolumeClassNo
    # 'VolumeClassNo': '',
    # 档号 VolumeFileNo
    'VolumeFileNo': '',
    # 卷号 VolumeNo
    # 'VolumeNo': '',
    # 开始-结束时间
    # 'VolumeBeginDate': nowDateStr(),
    # 'VolumeEndDate': nowDateStr(),
    # 分类名称-VolumeName
    'VolumeName': '',
    # 卷类型-VolumeType
    'VolumeType': 0,
    # 编辑时间-VolumeEditDatetime
    # 'VolumeEditDatetime': nowDateTimeStr(),
    # 编辑人-VolumeEditor
    # 'VolumeEditor': '',
    # 卷内目录
    'PageList': []
}

PROJECT_DICT3 = {
    # 开始页码
    'PageBegin': 0,
    # 结束页码
    'PageEnd': 0,
    # 开始图页
    'ImageBegin': 0,
    # 结束图页
    'ImageEnd': 0,
    # 名称
    'PageName': ''
}


class MyParser(ConfigParser):
    "Inherit from built-in class: ConfigParser"

    def optionxform(self, optionstr):
        "Rewrite without lower()"
        return optionstr


class fileConf():
    def __init__(self, file):
        self.initVar()
        self.config = MyParser()
        self.name = file
        self.readConf()

    def initVar(self):
        # 设计配置
        self.varConf = {'FileLocPath': '',
                        'FileExcept': 'db',
                        'Logo': '',
                        'Title': '',
                        'TabTitle': '',
                        'CurTab': 0,
                        'MaxPageMultiple': 10,
                        'WindowMax': 0}

        self.fileConf = {}

    def getConfig(self, section, key):
        return self.config.get(section, key)

    def readConf(self):
        self.config.read(self.name, 'utf-8')
        # [CONF]
        for k in self.varConf:
            try:
                str = self.getConfig('CONF', k)
                if isinstance(self.varConf[k], int):
                    self.varConf[k] = int(str)
                else:
                    self.varConf[k] = str
            except:
                self.writeConf('MaxPageMultiple', self.varConf[k])
        # [FILE]
        flist = self.config.items('FILE')
        for d in flist:
            if len(d) == 2:
                self.fileConf[d[0]] = d[1].split(',')
        # print(self.fileConf)

    def writeConf(self, key, value):
        self.config.set('CONF', key, str(value))
        with open(self.name, 'w', encoding='utf-8') as f:
            self.config.write(f)


class fileName(QMainWindow, Ui_NameWindow):
    beforeCloseSignal = pyqtSignal(str)

    def __init__(self, parent=None, conf=None):
        super(fileName, self).__init__(parent)
        self.setupUi(self)
        self.conf = conf
        self.init()

    def flushList(self):
        self.listWidget1.clear()
        self.listWidget2.clear()
        self.listWidget3.clear()
        self.pos1 = 0
        self.pos2 = 0
        self.pos3 = 0
        self.list1 = []
        self.list2 = {}
        self.list3 = {}
        self.curName = ''
        for k, v in self.conf.items():
            k1 = int(k)
            k2 = int(v[0])
            if k2 == 0 and v[1] == '':
                # 一级目录
                self.list1.append([k1, v[2]])
            elif k2 > 0 and v[1] == '':
                # 二级目录
                if k2 not in self.list2.keys():
                    self.list2[k2] = []
                self.list2[k2].append([k1, v[2]])
            else:
                # 文件
                if k2 not in self.list3.keys():
                    self.list3[k2] = []
                self.list3[k2].append([k1, v[1], v[2]])
        # 设置一级目录，当前行
        for d in self.list1:
            self.listWidget1.addItem(QListWidgetItem(d[1]))
        self.listWidget1.setCurrentRow(self.pos1)

    def selectListFile1(self, row):
        self.pos1 = row
        # print('list1 -> %d' % (row))
        k = self.list1[row][0]
        # 设置二级目录
        self.listWidget2.clear()
        for d in self.list2[k]:
            self.listWidget2.addItem(QListWidgetItem(d[1]))
        if self.pos2 >= len(self.list2[k]):
            self.pos2 = 0
        self.listWidget2.setCurrentRow(self.pos2)

    def selectListFile2(self, row):
        if row < 0:
            return
        self.pos2 = row
        # print('list2 -> %d' % (row))
        k1 = self.list1[self.pos1][0]
        k2 = self.list2[k1][row][0]
        # 设置三级文件
        self.listWidget3.clear()
        for d in self.list3[k2]:
            self.listWidget3.addItem(QListWidgetItem('%s %s' % (d[1], d[2])))
        if self.pos3 >= len(self.list3[k2]):
            self.pos3 = 0
        self.listWidget3.setCurrentRow(self.pos3)

    def selectListFile3(self, row):
        if row < 0:
            return
        # print('list3 -> %d' % (row))
        self.pos3 = row
        k1 = self.list1[self.pos1][0]
        k2 = self.list2[k1][self.pos2][0]
        self.curName = self.list3[k2][self.pos3][2]

    def init(self):
        self.setWindowTitle('请选择文件分类')
        self.pushButtonOk.clicked.connect(self.ok)
        self.pushButtonCancel.clicked.connect(self.cancel)
        self.listWidget1.currentRowChanged.connect(self.selectListFile1)
        self.listWidget2.currentRowChanged.connect(self.selectListFile2)
        self.listWidget3.currentRowChanged.connect(self.selectListFile3)
        self.flushList()

    def ok(self):
        self.beforeCloseSignal.emit(self.curName)
        self.close()

    def cancel(self):
        self.beforeCloseSignal.emit('')
        self.close()


class fileImage(QMainWindow, Ui_ImageWindow):
    beforeCloseSignal = pyqtSignal(int)

    def __init__(self, parent=None, title=None):
        super(fileImage, self).__init__(parent)
        self.setupUi(self)
        if title != None:
            self.title = title
        else:
            self.title = '图片预览'
        self.init()

    def closeEvent(self, event):
        self.beforeCloseSignal.emit(1)
        event.accept()

    def init(self):
        self.imageName = ''
        self.setWindowTitle(self.title)
        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.beforeCloseSignal.emit(0)

    def resizeEvent(self, event):
        # 当窗口大小变化时，重新计算并缩放图像
        self.flushImage(self.imageName)

    def flushImage(self, name):
        self.imageName = name
        info = getImgFile(name)
        if info[1] == 0 or info[2] == 0:
            self.setWindowTitle('%s -> %s' % (self.title, name))
            self.labelImage.setPixmap(QPixmap(''))
            self.labelImage.setText('非有效图片文件')
        else:
            self.setWindowTitle(
                '%s -> %s [%dx%d %d,%d %s]' % (self.title, name, info[1], info[2], info[3], info[4], getColor(info[5])))
            showLabelImage(self.scrollArea, self.labelImage, name, True)


class fileCache(QMainWindow, Ui_CacheWindow):
    beforeCloseSignal = pyqtSignal(int)

    def __init__(self, parent=None):
        super(fileCache, self).__init__(parent)
        self.setupUi(self)
        self.init()

    def init(self):
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.pushButtonOk.clicked.connect(self.ok)

    def ok(self):
        if self.radioButtonNoChange.isChecked():
            self.beforeCloseSignal.emit(0)
        if self.radioButtonHaveChange.isChecked():
            self.beforeCloseSignal.emit(1)
        self.close()


# 定义
class CustomTreeWidget(QTreeWidget):
    def keyPressEvent(self, event):
        print("keyPressEvent")
        if event.key() == Qt.Key.Key_Up:
            print("向上键按下")
        elif event.key() == Qt.Key.Key_Down:
            print("向下键按下")
        else:
            super(CustomTreeWidget, self).keyPressEvent(event)


class fileRun(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(fileRun, self).__init__(parent)

        # self.treeWidgetProject = CustomTreeWidget(self)
        # self.setCentralWidget(self.treeWidgetProject)
        # print("定义treeWidget")

        self.setupUi(self)
        self.config = fileConf('fileLoc.ini')
        self.initVar()
        self.init()
        self.initUI()

    def keyPressEvent(self, event):
        # print("keyPressEvent %d %d" % (event.key(), event.modifiers() & Qt.ControlModifier))
        # if event.modifiers() & Qt.ControlModifier:
        if event.key() in (Qt.Key_Up, Qt.Key_Down, Qt.Key_PageUp, Qt.Key_PageDown):
            self.treeWidgetProject.setFocus()
            return
        super().keyPressEvent(event)

    def initVar(self):
        self.fileLocPath = self.config.varConf['FileLocPath']
        self.fileExceptList = self.config.varConf['FileExcept'].split(',')
        # self.fileName = self.config.varConf['FileName']
        self.curTab = self.config.varConf['CurTab']
        # self.isSameName = False
        # self.syncPath = self.config.varConf['SyncPath']
        # self.inputFilePath = self.config.varConf['InputFilePath']
        # 档案项目字典-目录字典
        self.fileDict = {}
        self.fileFormDict = {}
        self.curProjectPath = ''
        self.curProjectDict = {}
        self.curVolumeDict = {}
        self.curVolumePageDict = {}
        self.curVolumePos = 0
        self.curVolumeTotal = 0
        # 档案项目列表
        self.fileList = []
        # 修改标记
        self.curType = 0
        self.curFile1 = ''
        self.curFile2 = ''
        self.isModify1 = False
        self.isModify2 = False
        self.curPagePos = -1
        self.curPageTotal = 0

    def init(self):
        self.curTime = datetime.datetime.now()
        if self.config.varConf['WindowMax'] > 0:
            self.showMaximized()
        self.setWindowIcon(QIcon(logo(self.config.varConf['Logo'])))
        self.setWindowTitle('%s        版本号[%s]' % (self.config.varConf['Title'], ver))
        # 图片窗口
        self.imageWindow = None
        # 档案路径
        if os.path.isdir(self.fileLocPath):
            self.lineEditFilePath.setText(self.fileLocPath)
        else:
            self.fileLocPath = ''
        # 档案名称
        # self.lineEditFileName.setText(self.fileName)
        # 导出
        # if os.path.isdir(self.syncPath):
        #     self.lineEditSyncPath.setText(self.syncPath)
        # else:
        #     self.syncPath = ''
        # 导入
        # if os.path.isdir(self.inputFilePath):
        #     self.lineEditInputFilePath.setText(self.inputFilePath)
        # else:
        #     self.inputFilePath = ''

    def initUI(self):
        # 捕获鼠标
        # self.setMouseTracking(True)
        self.lineEditPageName.installEventFilter(self)
        self.labelImage.installEventFilter(self)
        # 保管期限，密级
        setComboBoxHeight(self.comboBoxProjectKeepLimit, 18)
        setComboBoxHeight(self.comboBoxProjectSecretDegree, 18)
        setComboBoxHeight(self.comboBoxVolumeType, 18)
        # 同目录名
        # self.checkBoxSameName.toggled.connect(self.fileSameName)
        # 选择目录
        self.pushButtonFilePath.clicked.connect(self.choiceFilePath)
        # 读取,缓存
        self.pushButtonReadFile.clicked.connect(self.readFile)
        # self.pushButtonClearCache.clicked.connect(self.clearCache)
        # 目录
        self.treeWidgetProject.setColumnCount(6)
        self.treeWidgetProject.setItemsExpandable(True)
        self.treeWidgetProject.expandAll()
        self.treeWidgetProject.setHeaderLabels(
            [' 序号 ', ' 项目/工程目录 ', '卷数', ' 图片信息 ', ' 页码 ', '   状态   '])
        self.treeWidgetProject.itemClicked.connect(self.showTreeProject)
        self.treeWidgetProject.currentItemChanged.connect(self.selectTreeProject)
        # self.treeWidgetProject.itemEntered.connect(self.hoverTreeProject)
        for i in range(6):
            self.treeWidgetProject.headerItem().setTextAlignment(i, Qt.AlignCenter)
            self.treeWidgetProject.header().setSectionResizeMode(i, QHeaderView.ResizeToContents)
        self.checkBoxProjectSameHand.toggled.connect(self.projectSameHand)
        self.checkBoxProjectSameConstruct.toggled.connect(self.projectSameConstruct)
        # 案卷著录说明
        # 卷列
        self.pageColWidth = [65, 65, 65, 65, 200]
        for i in range(len(self.pageColWidth)):
            self.tableWidgetVolumePage.setColumnWidth(i, self.pageColWidth[i])
        self.pageColHeadList = []
        for i in range(self.tableWidgetVolumePage.columnCount()):
            self.pageColHeadList.append(self.tableWidgetVolumePage.horizontalHeaderItem(i).text())
        self.tableWidgetVolumePage.setHorizontalHeaderLabels(self.pageColHeadList)
        self.tableWidgetVolumePage.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.tableWidgetVolumePage.clicked.connect(self.onPageChoice)
        # 案卷-新增、还原、删除、保存
        self.pushButtonPageInsert.clicked.connect(self.pageInsert)
        self.pushButtonPageRestore.clicked.connect(self.pageRestore)
        self.pushButtonPageModify.clicked.connect(self.pageModify)
        self.pushButtonPageDelete.clicked.connect(self.pageDelete)
        self.pushButtonPageFlush.clicked.connect(self.pageFlush)
        # self.pushButtonPageSave.clicked.connect(self.pageSave)
        # 项目：初始，还原，保存
        self.pushButtonProjectReset.clicked.connect(self.projectReset)
        self.pushButtonProjectRestore.clicked.connect(self.projectRestore)
        self.pushButtonProjectSave.clicked.connect(self.projectSave)
        # 案卷：初始，还原，保存
        self.pushButtonVolumeReset.clicked.connect(self.volumeReset)
        self.pushButtonVolumeRestore.clicked.connect(self.volumeRestore)
        self.pushButtonVolumePageSave.clicked.connect(self.volumePageSave)
        # self.pushButtonProjectStat.hide()
        # self.pushButtonProjectStat.clicked.connect(self.projectStat)
        # 核查，修正，著录，导出，导入
        tlist = self.config.varConf['TabTitle'].split(',')
        for i, t in enumerate(tlist):
            self.tabWidget.setTabText(i, t)
        self.tabWidget.currentChanged.connect(self.tabFunc)
        self.tabWidget.setCurrentIndex(self.curTab)
        # self.tabCheck ：开始核查
        self.pushButtonCheck.clicked.connect(self.projectCheck)
        # 图片左转，右转
        self.pushButtonRotateLeft.setEnabled(False)
        self.pushButtonRotateRight.setEnabled(False)
        self.pushButtonRotateLeft.clicked.connect(self.imageRotateLeft)
        self.pushButtonRotateRight.clicked.connect(self.imageRotateRight)
        # self.tabCorrect
        # self.tabDescription：
        # self.tabExport
        # self.pushButtonSyncPath.clicked.connect(self.choiceSyncPath)
        # self.pushButtonSync.clicked.connect(self.syncBegin)
        # self.tabImport
        # self.pushButtonInputFilePath.clicked.connect(self.choiceInputFilePath)
        # self.pushButtonInput.clicked.connect(self.inputBegin)
        # comboBoxVolumeType
        self.comboBoxVolumeType.currentIndexChanged.connect(self.changeVolumeType)

    def closeEvent(self, event):
        if self.imageWindow != None:
            self.imageWindow.close()
        event.accept()

    def timeDiff(self):
        t = datetime.datetime.now()
        m = (t - self.curTime).microseconds
        if m > 100:
            # print(m)
            self.curTime = t
            return True
        return False

    # 清除CACHE
    def clearCache(self):
        deleteFile(pathJoin(self.fileLocPath, 'cache.lst'))

    def tabFunc(self, index):
        self.curTab = index
        curName = self.tabWidget.tabText(index)
        if self.curTab != self.config.varConf['CurTab']:
            self.config.writeConf('CurTab', self.curTab)
        print(curName)

    # 开始核查
    def projectCheck(self):
        if len(self.fileDict) == 0 or len(self.fileList) == 0:
            showBox(self, ' 无项目目录及数据文件 ！！！')
            return
        # 清除缓存

        self.checkList = []
        # 文件夹名称
        # self.checkList.append(0)
        # self.checkList.append(1)
        # 文件夹空
        # self.checkList.append(5)
        # 文件夹结构
        # self.checkList.append(9)
        # 文件可读
        # self.checkList.append(10)
        # 文件扩展名
        # self.checkList.append(20)
        # 文件命名
        # self.checkList.append(30)
        # self.checkList.append(31)
        # 文件DPI
        # self.checkList.append(40)
        # 文件颜色
        if self.checkBoxCheckFileColor.isChecked():
            self.checkList.append(60)
        if self.checkBoxCheckFileGray.isChecked():
            self.checkList.append(61)
        if len(self.checkList) == 0:
            showBox(self, ' 请选择图像色彩 ！！！')
            return
        self.lineEditCheckTotal.setText('')
        self.textEditCheckResult.clear()
        self.checkErr = 0
        self.checkErrLog = nowDateStr() + '-err.lst'
        saveLog('', self.fileLocPath, log=self.checkErrLog)
        # self.pushButtonClearCache.setEnabled(False)
        self.pushButtonFilePath.setEnabled(False)
        self.pushButtonReadFile.setEnabled(False)
        self.pushButtonCheck.setEnabled(False)
        self.progressBarCheck.reset()
        self.checkThread = checkFileThread(self.fileLocPath,
                                           self.checkList,
                                           self.fileDict,
                                           self.fileList,
                                           self.fileExceptList)
        self.checkThread.update_item.connect(self.checkShow)
        self.checkThread.start()

    def checkShow(self, flist):
        if len(flist) == 1:
            self.progressBarCheck.setValue(int(flist[0]))
            return
        if len(flist) == 0:
            if self.checkErr == 0:
                # 无错误
                # 检查是否冗余文件
                self.cleanFile()
                # 存储CACHE
                self.writeCache()
                self.lineEditCheckTotal.setText('核查无错误')
            self.progressBarCheck.setValue(100)
            self.pushButtonCheck.setEnabled(True)
            self.pushButtonFilePath.setEnabled(True)
            self.pushButtonReadFile.setEnabled(True)
            # self.pushButtonClearCache.setEnabled(True)
            return
        # 错误
        if len(flist) == 3:
            self.checkErr += 1
            # msg = '%d,%d,[%s],[%s]' % (self.checkErr, flist[0], flist[1], flist[2])
            msg = '%d,[%s],[%s]' % (self.checkErr, flist[1], flist[2])
            self.lineEditCheckTotal.setText('出现错误数 %d' % (self.checkErr))
            self.textEditCheckResult.moveCursor(QTextCursor.Start)
            self.textEditCheckResult.insertPlainText(nowTimeStr() + '  ' + msg + '\n')
            saveLog(msg, self.fileLocPath, log=self.checkErrLog)

    # 项目：初始，还原，保存
    def projectReset(self):
        if self.curType == 0:
            self.initProjectForm()
        self.projectEdit()

    def projectRestore(self):
        if self.curType == 0:
            self.curProjectDict = self.readFormFile(self.curFile1, PROJECT_DICT1)
        self.projectEdit()

    def projectEdit(self):
        if self.curType == 0:
            self.isModify1 = True
            self.isModify2 = False
            self.initProjectFormUI()
            self.setProjectFormUI()
        self.setImageFormUI()

    # 必填是否为空
    def isProjectSpace(self):
        info = ''
        if len(self.curProjectDict['ProjectName']) == 0:
            info += '\"工程名称\"，'
        if len(self.curProjectDict['ProjectAddr']) == 0:
            info += '\"工程地点\"，'
        if len(self.curProjectDict['ProjectBuildArea']) == 0:
            info += '\"建筑面积\"，'
        if len(self.curProjectDict['ProjectHandUnit']) == 0:
            info += '\"移交单位\"，'
        if len(self.curProjectDict['ProjectBuildUnit']) == 0:
            info += '\"建设单位\"，'
        if len(self.curProjectDict['ProjectConstructUnit']) == 0:
            info += '\"施工单位\"，'
        if len(self.curProjectDict['ProjectAuthorUnit']) == 0:
            info += '\"编制单位\"，'
        if len(self.curProjectDict['ProjectEditor']) == 0:
            info += '\"资料员\"，'
        if len(info) > 0:
            info += '为必填项\n  请著录后再保存！！！'
            showBox(self, info)
            return True
        return False

    def projectSave(self):
        if self.curType == 0:
            # self.isModify1 = False
            # self.setProjectFormUI()
            self.readProjectFormUI()
            if not self.isProjectSpace():
                self.fileFormDict[self.curFile1] = self.curProjectDict
                name = self.getFormFile(self.curFile1)
                self.curProjectDict['ProjectPath'] = name
                self.writeFormFile(self.curFile1, name)
                self.curItem.setText(5, ' %s ' % (self.isFormFile(self.curFile1)))

    # 案卷：初始，还原，保存
    def volumeReset(self):
        if self.curType == 1:
            self.initVolumeForm()
        self.volumeEdit()

    def volumeRestore(self):
        if self.curType == 1:
            vDict = self.readFormFile(self.curFile2, PROJECT_DICT2)
            self.curVolumeDict['VolumePath'] = vDict['VolumePath']
            self.curVolumeDict['VolumeTitle'] = vDict['VolumeTitle']
            self.curVolumeDict['VolumeFileNo'] = vDict['VolumeFileNo']
            self.curVolumeDict['VolumeName'] = vDict['VolumeName']
            self.curVolumeDict['VolumeType'] = vDict['VolumeType']
        self.volumeEdit()

    def volumeEdit(self):
        if self.curType == 1:
            self.isModify1 = False
            self.isModify2 = True
            self.initVolumeFormUI()
            self.setVolumeFormUI()
        self.setImageFormUI()

    def projectStat(self):
        n11 = 0
        n12 = 0
        n21 = 0
        n22 = 0
        for k, v in self.fileDict.items():
            if v[0] == 1 and self.curFile1 in k:
                form = self.readFormFile(k, None)
                if not form:
                    continue
                pos = v[1]
                if form['VolumeType'] == 0:
                    # 文字
                    n11 += 1
                    n12 += len(self.fileList[pos])
                else:
                    # 图片
                    n21 += 1
                    n22 += len(self.fileList[pos])
        self.curProjectDict['ProjectWordVolNums'] = n11
        self.curProjectDict['ProjectWordFrameNums'] = n12
        self.curProjectDict['ProjectPicVolNums'] = n21
        self.curProjectDict['ProjectPicFrameNums'] = n22

    # 同目录名
    # def fileSameName(self, checked):
    #     self.isSameName = checked
    #     self.lineEditFileName.setReadOnly(checked)
    #     self.lineEditFileName.setText(os.path.basename(self.fileLocPath) if self.isSameName else self.fileName)

    # 选择目录
    def choiceFilePath(self):
        path = QFileDialog.getExistingDirectory(self, " 选择档案管理目录 ", self.fileLocPath)
        if os.path.exists(path):
            if path != self.fileLocPath:
                self.fileLocPath = path
                self.config.writeConf('FileLocPath', path)
                self.lineEditFilePath.setText(self.fileLocPath)
                # 清空目录
                self.treeWidgetProject.blockSignals(True)
                self.treeWidgetProject.clear()
                self.fileDict.clear()
                self.fileList.clear()
                self.treeWidgetProject.blockSignals(False)

    # 刷新
    def pageFlush(self):
        pageList = self.curVolumeDict['PageList']
        self.tableWidgetVolumePage.clear()
        self.tableWidgetVolumePage.setRowCount(len(pageList))
        # 刷新标题
        self.tableWidgetVolumePage.setHorizontalHeaderLabels(self.pageColHeadList)
        self.tableWidgetVolumePage.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        if len(pageList) == 0:
            return
        #
        for i, s in enumerate(pageList):
            # 0
            item1 = QTableWidgetItem('%d页' % s['PageBegin'])
            self.tableWidgetVolumePage.setItem(i, 0, item1)
            item1.setTextAlignment(Qt.AlignCenter)
            # 1
            item2 = QTableWidgetItem('%d页' % s['PageEnd'])
            self.tableWidgetVolumePage.setItem(i, 1, item2)
            item2.setTextAlignment(Qt.AlignCenter)
            # 2
            if 'ImageBegin' not in s:
                s['ImageBegin'] = 0
            item3 = QTableWidgetItem('%d页' % s['ImageBegin'])
            self.tableWidgetVolumePage.setItem(i, 2, item3)
            item3.setTextAlignment(Qt.AlignCenter)
            # 3
            if 'ImageEnd' not in s:
                s['ImageEnd'] = 0
            item4 = QTableWidgetItem('%d页' % s['ImageEnd'])
            self.tableWidgetVolumePage.setItem(i, 3, item4)
            item4.setTextAlignment(Qt.AlignCenter)
            # 4
            item5 = QTableWidgetItem(s['PageName'])
            self.tableWidgetVolumePage.setItem(i, 4, item5)
            item5.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)

    # 卷内页码选择
    def onPageChoice(self, item):
        self.curPagePos = item.row()
        self.spinBoxPageBegin.setValue(self.curVolumeDict['PageList'][self.curPagePos]['PageBegin'])
        self.spinBoxPageEnd.setValue(self.curVolumeDict['PageList'][self.curPagePos]['PageEnd'])
        self.spinBoxImageBegin.setValue(self.curVolumeDict['PageList'][self.curPagePos]['ImageBegin'])
        self.spinBoxImageEnd.setValue(self.curVolumeDict['PageList'][self.curPagePos]['ImageEnd'])
        self.lineEditPageName.setText(self.curVolumeDict['PageList'][self.curPagePos]['PageName'])

    def isPageList(self):
        # 页码目录是否符合
        page = {}
        if self.spinBoxPageBegin.value() > self.spinBoxPageEnd.value():
            showBox(self, '案卷页码开始大于截止， 请重新选择 ！！！')
            return None
        if self.spinBoxImageBegin.value() > self.spinBoxImageEnd.value():
            showBox(self, '图片页码开始大于截止， 请重新选择 ！！！')
            return None
        if len(self.lineEditPageName.text()) == 0:
            showBox(self, '案卷页\"类别\"为必填项， 请选择后再新增 ！！！')
            return None
        page['PageBegin'] = self.spinBoxPageBegin.value()
        page['PageEnd'] = self.spinBoxPageEnd.value()
        page['ImageBegin'] = self.spinBoxImageBegin.value()
        page['ImageEnd'] = self.spinBoxImageEnd.value()
        page['PageName'] = self.lineEditPageName.text()
        plist = [0] * self.curPageTotal * self.config.varConf['MaxPageMultiple']
        ilist = [0] * self.curPageTotal
        pb = False
        ib = False
        # index = 0
        for i, p in enumerate(self.curVolumeDict['PageList']):
            if self.curPagePos >= 0:
                if self.curPagePos == i:
                    continue
            pm1 = p['PageBegin']
            pm2 = p['PageEnd']
            im1 = p['ImageBegin']
            im2 = p['ImageEnd']
            # if page['PageBegin'] > pm1:
            #     index += 1
            for i in range(pm1 - 1, pm2):
                if plist[i] == 0:
                    plist[i] = 1
            for i in range(im1 - 1, im2):
                if ilist[i] == 0:
                    ilist[i] = 1
        for i in range(page['PageBegin'] - 1, page['PageEnd']):
            if plist[i] == 1:
                pb = True
        if pb:
            showBox(self, ' 目录内页码目录出现交叉，重新配置')
            return None
        for i in range(page['ImageBegin'] - 1, page['ImageEnd']):
            if ilist[i] == 1:
                ib = True
        if ib:
            showBox(self, ' 目录内图片页出现交叉，重新配置')
            return None
        return page

    def pageInsert(self):
        self.curPagePos = -1
        page = self.isPageList()
        if page is None:
            return
        self.curVolumeDict['PageList'].insert(len(self.curVolumeDict['PageList']), page)
        self.pageFlush()

    def pageRestore(self):
        vDict = self.readFormFile(self.curFile2, PROJECT_DICT2)
        self.curVolumeDict['PageList'] = vDict['PageList'].copy()
        self.curPagePos = -1
        self.pageFlush()

    def pageModify(self):
        if self.curPagePos < 0:
            return
        print('modift %d' % self.curPagePos)
        if self.isPageList() is None:
            return
        page = self.curVolumeDict['PageList'][self.curPagePos]
        page['PageBegin'] = self.spinBoxPageBegin.value()
        page['PageEnd'] = self.spinBoxPageEnd.value()
        page['ImageBegin'] = self.spinBoxImageBegin.value()
        page['ImageEnd'] = self.spinBoxImageEnd.value()
        page['PageName'] = self.lineEditPageName.text()
        self.pageFlush()

    def pageDelete(self):
        if self.curPagePos < 0:
            return
        self.curVolumeDict['PageList'].pop(self.curPagePos)
        self.pageFlush()

    # 必填是否为空
    def isVolumeSpace(self):
        info = ''
        if len(self.curVolumeDict['VolumeTitle']) == 0:
            info += '\"案卷提名\"，'
        if len(self.curVolumeDict['VolumeName']) == 0:
            info += '\"工程类名\"，'
        if self.tableWidgetVolumePage.rowCount() == 0:
            info += '\"案卷页\"，'
        if len(info) > 0:
            info += '为必填项\n  请著录后再保存！！！'
            showBox(self, info)
            return True
        return False

    def volumePageSave(self):
        if self.curType == 1:
            # self.isModify2 = False
            # self.setVolumeFormUI()
            self.readVolumeFormUI()
            if not self.isVolumeSpace():
                self.fileFormDict[self.curFile2] = self.curVolumeDict
                name = self.getFormFile(self.curFile2)
                self.curVolumeDict['VolumePath'] = name
                self.writeFormFile(self.curFile2, name)
                self.curItem.setText(5, ' %s ' % (self.isFormFile(self.curFile2)))
                # 页码刷新
                vDictPage = self.curVolumeDict['PageList']
                # 当前页子项目遍历
                for child in range(self.curItem.childCount()):
                    child_item = self.curItem.child(child)
                    # child_item.setText(2, ' %d ' % (i + 1))
                    # child_item.setText(3, ' %s ' % (os.path.basename(f)))
                    # 4-页数
                    p = self.getPage(child + 1, vDictPage)
                    if p > 0:
                        child_item.setText(4, ' %d ' % (p))
                    else:
                        child_item.setText(4, '  ')
                    # child_item.setText(5, ' %s ' % (isImgOk(self.fileList[v[1]][f])))

    # 著录字典初始
    def initProjectForm(self, name=''):
        if name in self.fileDict.keys():
            self.curProjectDict = self.fileFormDict[name]
            for k, v in PROJECT_DICT1.items():
                if k not in self.curProjectDict.keys():
                    self.curProjectDict[k] = v
        else:
            self.curProjectDict = PROJECT_DICT1.copy()
        if self.curProjectDict['ProjectPath'] == '':
            self.curProjectDict['ProjectPath'] = name

    def initProjectFormUI(self):
        self.labelProjectVolTotal.setText('%d' % (self.curVolumeTotal))
        # 分类号
        self.lineEditProjectClassNo.setText(self.curProjectDict['ProjectClassNo'])
        # 工程名称-ProjectName
        self.lineEditProjectName.setText(self.curProjectDict['ProjectName'])
        # 工程地点-ProjectAddr
        self.lineEditProjectAddr.setText(self.curProjectDict['ProjectAddr'])
        # 建筑面积-ProjectBuildArea
        self.lineEditProjectBuildArea.setText(self.curProjectDict['ProjectBuildArea'])
        # 结构类型-ProjectStructType
        # self.lineEditProjectStructType.setText(self.curProjectDict['ProjectStructType'])
        # 保管期限-ProjectKeepLimit
        self.comboBoxProjectKeepLimit.setCurrentIndex(self.curProjectDict['ProjectKeepLimit'])
        # 密级-ProjectSecretDegree
        self.comboBoxProjectSecretDegree.setCurrentIndex(self.curProjectDict['ProjectSecretDegree'])
        # 移交单位-ProjectHandUnit
        self.lineEditProjectHandUnit.setText(self.curProjectDict['ProjectHandUnit'])
        # 建设单位-ProjectBuildUnit
        self.lineEditProjectBuildUnit.setText(self.curProjectDict['ProjectBuildUnit'])
        self.checkBoxProjectSameHand.setChecked(False)
        # 施工单位-ProjectConstructUnit
        self.lineEditProjectConstructUnit.setText(self.curProjectDict['ProjectConstructUnit'])
        # 编制单位-ProjectAuthorUnit
        self.lineEditProjectAuthorUnit.setText(self.curProjectDict['ProjectAuthorUnit'])
        self.checkBoxProjectSameConstruct.setChecked(False)
        # 开工日期-ProjectStartWorkDate
        self.dateEditProjectStartWorkDate.setDate(getDate(self.curProjectDict['ProjectStartWorkDate']))
        # 竣工日期-ProjectCompleteDate
        self.dateEditProjectCompleteDate.setDate(getDate(self.curProjectDict['ProjectCompleteDate']))
        # 进馆日期-ProjectEnterDate
        self.dateEditProjectEnterDate.setDate(getDate(self.curProjectDict['ProjectEnterDate']))
        # 位置X1
        self.doubleSpinBoxProjectLocateX1.setValue(self.curProjectDict['ProjectLocateX1'])
        # 位置Y1
        self.doubleSpinBoxProjectLocateY1.setValue(self.curProjectDict['ProjectLocateY1'])
        # 位置X2
        self.doubleSpinBoxProjectLocateX2.setValue(self.curProjectDict['ProjectLocateX2'])
        # 位置Y2
        self.doubleSpinBoxProjectLocateY2.setValue(self.curProjectDict['ProjectLocateY2'])
        # 位置X3
        self.doubleSpinBoxProjectLocateX3.setValue(self.curProjectDict['ProjectLocateX3'])
        # 位置Y3
        self.doubleSpinBoxProjectLocateY3.setValue(self.curProjectDict['ProjectLocateY3'])
        # 位置X4
        self.doubleSpinBoxProjectLocateX4.setValue(self.curProjectDict['ProjectLocateX4'])
        # 位置Y4
        self.doubleSpinBoxProjectLocateY4.setValue(self.curProjectDict['ProjectLocateY4'])
        # 存放地址-ProjectStoreAddr
        # self.lineEditProjectStoreAddr.setText(self.curProjectDict['ProjectStoreAddr'])
        # 编辑时间-ProjectEditDatetime
        # self.dateTimeEditProjectEditDateTime.setDateTime(getDateTime(self.curProjectDict['ProjectEditDatetime']))
        # 资料员-ProjectEditor
        self.lineEditProjectEditor.setText(self.curProjectDict['ProjectEditor'])

    # 同移交单位
    def projectSameHand(self, checked):
        if self.isModify1:
            if checked:
                # 建设单位-ProjectBuildUnit
                self.lineEditProjectBuildUnit.setText(self.lineEditProjectHandUnit.text())
            else:
                # 建设单位-ProjectBuildUnit
                self.lineEditProjectBuildUnit.setText(self.curProjectDict['ProjectBuildUnit'])

    # 同施工单位
    def projectSameConstruct(self, checked):
        if self.isModify1:
            if checked:
                # 编制单位-ProjectAuthorUnit
                self.lineEditProjectAuthorUnit.setText(self.lineEditProjectConstructUnit.text())
            else:
                # 编制单位-ProjectAuthorUnit
                self.lineEditProjectAuthorUnit.setText(self.curProjectDict['ProjectAuthorUnit'])

    def flushFormUI(self):
        info = ['项目', '案卷', '信息']
        self.labelState.setText('%s%s' % (info[self.curType],
                                          '编辑' if self.isModify1 or self.isModify2 else '查询'))

    def showProjectTotal(self):
        # 文字卷数-ProjectWordVolNums
        self.labelProjectWordVolNums.setText('%d' % (self.curProjectDict['ProjectWordVolNums']))
        # 文字张数-ProjectWordFrameNums
        self.labelProjectWordFrameNums.setText('%d' % (self.curProjectDict['ProjectWordFrameNums']))
        # 图纸卷数-ProjectPicVolNums
        self.labelProjectPicVolNums.setText('%d' % (self.curProjectDict['ProjectPicVolNums']))
        # 图纸张数-ProjectPicFrameNums
        self.labelProjectPicFrameNums.setText('%d' % (self.curProjectDict['ProjectPicFrameNums']))

    def setProjectFormUI(self):
        self.flushFormUI()
        # 分类好-ProjectClassNo
        self.lineEditProjectClassNo.setEnabled(self.isModify1)
        self.lineEditProjectClassNo.setReadOnly(not self.isModify1)
        # 工程名称-ProjectName
        self.lineEditProjectName.setEnabled(self.isModify1)
        self.lineEditProjectName.setReadOnly(not self.isModify1)
        # 工程地点-ProjectAddr
        self.lineEditProjectAddr.setEnabled(self.isModify1)
        self.lineEditProjectAddr.setReadOnly(not self.isModify1)
        # 建筑面积-ProjectBuildArea
        self.lineEditProjectBuildArea.setEnabled(self.isModify1)
        self.lineEditProjectBuildArea.setReadOnly(not self.isModify1)
        # 结构类型-ProjectStructType
        # self.lineEditProjectStructType.setEnabled(self.isModify1)
        # self.lineEditProjectStructType.setReadOnly(not self.isModify1)
        # 保管期限-ProjectKeepLimit
        self.comboBoxProjectKeepLimit.setEnabled(self.isModify1)
        # 密级-ProjectSecretDegree
        self.comboBoxProjectSecretDegree.setEnabled(self.isModify1)
        # 移交单位-ProjectHandUnit
        self.lineEditProjectHandUnit.setEnabled(self.isModify1)
        self.lineEditProjectHandUnit.setReadOnly(not self.isModify1)
        # 建设单位-ProjectBuildUnit
        self.lineEditProjectBuildUnit.setEnabled(self.isModify1)
        self.lineEditProjectBuildUnit.setReadOnly(not self.isModify1)
        self.checkBoxProjectSameHand.setEnabled(self.isModify1)
        # 施工单位-ProjectConstructUnit
        self.lineEditProjectConstructUnit.setEnabled(self.isModify1)
        self.lineEditProjectConstructUnit.setReadOnly(not self.isModify1)
        # 编制单位-ProjectAuthorUnit
        self.lineEditProjectAuthorUnit.setEnabled(self.isModify1)
        self.lineEditProjectAuthorUnit.setReadOnly(not self.isModify1)
        self.checkBoxProjectSameConstruct.setEnabled(self.isModify1)
        # 开工日期-ProjectStartWorkDate
        self.dateEditProjectStartWorkDate.setEnabled(self.isModify1)
        self.dateEditProjectStartWorkDate.setReadOnly(not self.isModify1)
        # 竣工日期-ProjectCompleteDate
        self.dateEditProjectCompleteDate.setEnabled(self.isModify1)
        self.dateEditProjectCompleteDate.setReadOnly(not self.isModify1)
        # 进馆日期-ProjectEnterDate
        self.dateEditProjectEnterDate.setEnabled(self.isModify1)
        self.dateEditProjectEnterDate.setReadOnly(not self.isModify1)
        # 位置X1
        self.doubleSpinBoxProjectLocateX1.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateX1.setReadOnly(not self.isModify1)
        # 位置Y1
        self.doubleSpinBoxProjectLocateY1.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateY1.setReadOnly(not self.isModify1)
        # 位置X2
        self.doubleSpinBoxProjectLocateX2.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateX2.setReadOnly(not self.isModify1)
        # 位置Y2
        self.doubleSpinBoxProjectLocateY2.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateY2.setReadOnly(not self.isModify1)
        # 位置X3
        self.doubleSpinBoxProjectLocateX3.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateX3.setReadOnly(not self.isModify1)
        # 位置Y3
        self.doubleSpinBoxProjectLocateY3.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateY3.setReadOnly(not self.isModify1)
        # 位置X4
        self.doubleSpinBoxProjectLocateX4.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateX4.setReadOnly(not self.isModify1)
        # 位置Y4
        self.doubleSpinBoxProjectLocateY4.setEnabled(self.isModify1)
        self.doubleSpinBoxProjectLocateY4.setReadOnly(not self.isModify1)
        # 文字卷数-ProjectWordVolNums
        # self.lineEditProjectWordVolNums.setEnabled(self.isModify1)
        # 文字张数-ProjectWordFrameNums
        # self.lineEditProjectWordFrameNums.setEnabled(self.isModify1)
        # 图纸卷数-ProjectPicVolNums
        # self.lineEditProjectPicVolNums.setEnabled(self.isModify1)
        # 图纸张数-ProjectPicFrameNums
        # self.lineEditProjectPicFrameNums.setEnabled(self.isModify1)
        # 存放地址-ProjectStoreAddr
        # self.lineEditProjectStoreAddr.setEnabled(self.isModify1)
        # self.lineEditProjectStoreAddr.setReadOnly(not self.isModify1)
        # 编辑时间-ProjectEditDatetime
        # self.dateTimeEditProjectEditDateTime.setEnabled(self.isModify1)
        # 资料员-ProjectEditor
        self.lineEditProjectEditor.setEnabled(self.isModify1)
        self.lineEditProjectEditor.setReadOnly(not self.isModify1)
        # 项目按钮
        self.pushButtonProjectReset.setEnabled(self.isModify1)
        self.pushButtonProjectRestore.setEnabled(self.isModify1)
        self.pushButtonProjectSave.setEnabled(self.isModify1)
        # 编辑聚焦
        # self.lineEditProjectClassNo.setFocus()

    def readProjectFormUI(self):
        # 分类号-ProjectClassNo
        self.curProjectDict['ProjectClassNo'] = self.lineEditProjectClassNo.text()
        # 工程名称-ProjectName
        self.curProjectDict['ProjectName'] = self.lineEditProjectName.text()
        # 工程地点-ProjectAddr
        self.curProjectDict['ProjectAddr'] = self.lineEditProjectAddr.text()
        # 建筑面积-ProjectBuildArea
        self.curProjectDict['ProjectBuildArea'] = self.lineEditProjectBuildArea.text()
        # 结构类型-ProjectStructType
        # self.curProjectDict['ProjectStructType'] = self.lineEditProjectStructType.text()
        # 保管期限-ProjectKeepLimit
        self.curProjectDict['ProjectKeepLimit'] = self.comboBoxProjectKeepLimit.currentIndex()
        # 密级-ProjectSecretDegree
        self.curProjectDict['ProjectSecretDegree'] = self.comboBoxProjectSecretDegree.currentIndex()
        # 移交单位-ProjectHandUnit
        self.curProjectDict['ProjectHandUnit'] = self.lineEditProjectHandUnit.text()
        # 建设单位-ProjectBuildUnit
        self.curProjectDict['ProjectBuildUnit'] = self.lineEditProjectBuildUnit.text()
        # 施工单位-ProjectConstructUnit
        self.curProjectDict['ProjectConstructUnit'] = self.lineEditProjectConstructUnit.text()
        # 编制单位-ProjectAuthorUnit
        self.curProjectDict['ProjectAuthorUnit'] = self.lineEditProjectAuthorUnit.text()
        # 开工日期-ProjectStartWorkDate
        self.curProjectDict['ProjectStartWorkDate'] = dateToStr(self.dateEditProjectStartWorkDate)
        # 竣工日期-ProjectCompleteDate
        self.curProjectDict['ProjectCompleteDate'] = dateToStr(self.dateEditProjectCompleteDate)
        # 进馆日期-ProjectEnterDate
        self.curProjectDict['ProjectEnterDate'] = dateToStr(self.dateEditProjectEnterDate)
        # 位置X1
        self.curProjectDict['ProjectLocateX1'] = self.doubleSpinBoxProjectLocateX1.value()
        # 位置Y1
        self.curProjectDict['ProjectLocateY1'] = self.doubleSpinBoxProjectLocateY1.value()
        # 位置X2
        self.curProjectDict['ProjectLocateX2'] = self.doubleSpinBoxProjectLocateX2.value()
        # 位置Y2
        self.curProjectDict['ProjectLocateY2'] = self.doubleSpinBoxProjectLocateY2.value()
        # 位置X3
        self.curProjectDict['ProjectLocateX3'] = self.doubleSpinBoxProjectLocateX3.value()
        # 位置Y3
        self.curProjectDict['ProjectLocateY3'] = self.doubleSpinBoxProjectLocateY3.value()
        # 位置X4
        self.curProjectDict['ProjectLocateX4'] = self.doubleSpinBoxProjectLocateX4.value()
        # 位置Y4
        self.curProjectDict['ProjectLocateY4'] = self.doubleSpinBoxProjectLocateY4.value()
        # 总卷数-ProjectVolTotal
        self.curProjectDict['ProjectVolTotal'] = self.curVolumeTotal
        # 文字卷数-ProjectWordVolNums
        # self.curProjectDict['ProjectWordVolNums'] = int(self.lineEditProjectWordVolNums.text())
        # 文字张数-ProjectWordFrameNums
        # self.curProjectDict['ProjectWordFrameNums'] = int(self.lineEditProjectWordFrameNums.text())
        # 图纸卷数-ProjectPicVolNums
        # self.curProjectDict['ProjectPicVolNums'] = int(self.lineEditProjectPicVolNums.text())
        # 图纸张数-ProjectPicFrameNums
        # self.curProjectDict['ProjectPicFrameNums'] = int(self.lineEditProjectPicFrameNums.text())
        # 存放地址-ProjectStoreAddr
        # self.curProjectDict['ProjectStoreAddr'] = self.lineEditProjectStoreAddr.text()
        # 编辑时间-ProjectEditDatetime
        # self.curProjectDict['ProjectEditDatetime'] = nowDateTimeStr()
        # 资料员-ProjectEditor
        self.curProjectDict['ProjectEditor'] = self.lineEditProjectEditor.text()

    # 卷信息的编辑
    def initVolumeForm(self, name=''):
        if name in self.fileDict.keys():
            self.curVolumeDict = self.fileFormDict[name]
            # 字典深拷贝 2024.4.30
            for k, v in copy.deepcopy(PROJECT_DICT2).items():
                if k not in self.curVolumeDict.keys():
                    self.curVolumeDict[k] = v
        else:
            self.curVolumeDict['VolumePath'] = ''
            self.curVolumeDict['VolumeTitle'] = ''
            self.curVolumeDict['VolumeFileNo'] = ''
            self.curVolumeDict['VolumeName'] = ''
            self.curVolumeDict['VolumeType'] = 0
        if self.curVolumeDict['VolumePath'] == '':
            self.curVolumeDict['VolumePath'] = name

    def initVolumeFormUI(self):
        m = self.config.varConf['MaxPageMultiple']
        self.labelPageTotal.setText('%d' % (self.curPageTotal))
        self.spinBoxPageBegin.setMaximum(self.curPageTotal * m)
        self.spinBoxPageEnd.setMaximum(self.curPageTotal * m)
        self.spinBoxImageBegin.setMaximum(self.curPageTotal)
        self.spinBoxImageEnd.setMaximum(self.curPageTotal)
        # 卷标题-VolumeTitle
        self.lineEditVolumeTitle.setText(self.curVolumeDict['VolumeTitle'])
        # 编制单位-VolumeAuthorUnit
        # self.lineEditVolumeAuthorUnit.setText(self.curVolumeDict['VolumeAuthorUnit'])
        try:
            # 分类号 lineEditVolumeClassNo
            # self.lineEditVolumeClassNo.setText(self.curVolumeDict['VolumeClassNo'])
            # 档号 lineEditVolumeFileNo
            self.lineEditVolumeFileNo.setText(self.curVolumeDict['VolumeFileNo'])
            # 卷号 lineEditVolumeNo
            # self.lineEditVolumeNo.setText(self.curVolumeDict['VolumeNo'])
        except Exception:
            # 分类号 lineEditVolumeClassNo
            # self.lineEditVolumeClassNo.setText(PROJECT_DICT2['VolumeClassNo'])
            # 档号 lineEditVolumeFileNo
            self.lineEditVolumeFileNo.setText(PROJECT_DICT2['VolumeFileNo'])
            # 卷号 lineEditVolumeNo
            # self.lineEditVolumeNo.setText(PROJECT_DICT2['VolumeNo'])
        # 开始-结束时间
        # self.dateEditVolumeBeginDate.setDate(getDate(self.curVolumeDict['VolumeBeginDate']))
        # self.dateEditVolumeEndDate.setDate(getDate(self.curVolumeDict['VolumeEndDate']))
        # 分类名称-VolumeName
        self.lineEditVolumeName.setText(self.curVolumeDict['VolumeName'])
        # 卷类型-VolumeType
        self.comboBoxVolumeType.setCurrentIndex(self.curVolumeDict['VolumeType'])
        # 编辑时间-VolumeEditDatetime
        # self.dateTimeEditVolumeEditDateTime.setDateTime(getDateTime(self.curVolumeDict['VolumeEditDatetime']))
        # 编辑人-VolumeEditor
        # self.lineEditVolumeEditor.setText(self.curVolumeDict['VolumeEditor'])
        self.pageFlush()

    # 退出文件选择
    def exitChoiceName(self, name):
        if len(name) > 0:
            self.lineEditPageName.setText(name)

    # 打开文件选择
    def choiceName(self):
        name = fileName(self, self.config.fileConf)
        name.beforeCloseSignal.connect(self.exitChoiceName)
        name.show()

    # 退出图片窗口
    def exitImageWindow(self, code):
        if code == 1:
            self.imageWindow = None

    # 打开图片窗口
    def showImage(self):
        if self.imageWindow == None:
            self.imageWindow = fileImage(self)
        self.imageWindow.beforeCloseSignal.connect(self.exitImageWindow)
        self.imageWindow.show()
        self.imageWindow.flushImage(self.curImage)

    def imageRotateLeft(self):
        self.pushButtonRotateLeft.setEnabled(False)
        imageRotate(self.curImage, Image.Transpose.ROTATE_90)
        showLabelImage(self.scrollArea, self.labelImage, self.curImage, True)
        self.pushButtonRotateLeft.setEnabled(True)

    def imageRotateRight(self):
        self.pushButtonRotateRight.setEnabled(False)
        imageRotate(self.curImage, Image.Transpose.ROTATE_270)
        showLabelImage(self.scrollArea, self.labelImage, self.curImage, True)
        self.pushButtonRotateRight.setEnabled(True)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.MouseButtonPress:
            if self.curType == 1 and obj == self.lineEditPageName:
                self.choiceName()
        if event.type() == QEvent.MouseButtonDblClick:
            if self.curType == 2 and obj == self.labelImage:
                self.showImage()
        return False

    def changeVolumeType(self, index):
        # 保存-统计
        self.projectSave()
        self.projectStat()
        self.showProjectTotal()

    def setVolumeFormUI(self):
        self.flushFormUI()
        # 卷标题-VolumeTitle
        self.lineEditVolumeTitle.setEnabled(self.isModify2)
        self.lineEditVolumeTitle.setReadOnly(not self.isModify2)
        # 编制单位-VolumeAuthorUnit
        # self.lineEditVolumeAuthorUnit.setEnabled(self.isModify2)
        # self.lineEditVolumeAuthorUnit.setReadOnly(not self.isModify2)
        # 分类号 lineEditVolumeClassNo
        # self.lineEditVolumeClassNo.setEnabled(self.isModify2)
        # self.lineEditVolumeClassNo.setReadOnly(not self.isModify2)
        # 档号 lineEditVolumeFileNo
        self.lineEditVolumeFileNo.setEnabled(self.isModify2)
        self.lineEditVolumeFileNo.setReadOnly(not self.isModify2)
        # 卷号 lineEditVolumeNo
        # self.lineEditVolumeNo.setEnabled(self.isModify2)
        # self.lineEditVolumeNo.setReadOnly(not self.isModify2)
        # 开始-结束时间
        # self.dateEditVolumeBeginDate.setEnabled(self.isModify2)
        # self.dateEditVolumeEndDate.setEnabled(self.isModify2)
        # self.dateEditVolumeBeginDate.setReadOnly(not self.isModify2)
        # self.dateEditVolumeEndDate.setReadOnly(not self.isModify2)
        # 分类名称-VolumeName
        self.lineEditVolumeName.setEnabled(self.isModify2)
        self.lineEditVolumeName.setReadOnly(not self.isModify2)
        # 卷类型-VolumeType
        self.comboBoxVolumeType.setEnabled(self.isModify2)
        # 编辑时间-VolumeEditDatetime
        # self.dateTimeEditVolumeEditDateTime.setEnabled(self.isModify2)
        # 编辑人-VolumeEditor
        # self.lineEditVolumeEditor.setEnabled(self.isModify2)
        # self.lineEditVolumeEditor.setReadOnly(not self.isModify2)
        #
        self.tableWidgetVolumePage.setEnabled(self.isModify2)
        self.spinBoxPageBegin.setEnabled(self.isModify2)
        self.spinBoxPageEnd.setEnabled(self.isModify2)
        self.spinBoxImageBegin.setEnabled(self.isModify2)
        self.spinBoxImageEnd.setEnabled(self.isModify2)
        self.lineEditPageName.setEnabled(self.isModify2)
        self.pushButtonPageInsert.setEnabled(self.isModify2 and self.curPageTotal > 0)
        self.pushButtonPageModify.setEnabled(self.isModify2 and self.curPageTotal > 0)
        self.pushButtonPageRestore.setEnabled(self.isModify2 and self.curPageTotal > 0)
        self.pushButtonPageDelete.setEnabled(self.isModify2 and self.curPageTotal > 0)
        self.pushButtonPageFlush.setEnabled(self.isModify2 and self.curPageTotal > 0)
        self.pushButtonVolumePageSave.setEnabled(self.isModify2)
        # 案卷按钮
        self.pushButtonVolumeReset.setEnabled(self.isModify2)
        self.pushButtonVolumeRestore.setEnabled(self.isModify2)
        # self.pushButtonVolumeSave.setEnabled(self.isModify2)
        # 编辑聚焦
        # self.lineEditVolumeFileNo.setFocus()

    def setImageFormUI(self):
        b = False
        if not self.isModify1 and not self.isModify2:
            info = getImgFile(self.curImage)
            self.labelProjectVolInfo.setText(os.path.basename(self.curImage))
            self.labelProjectVolResolution.setText('%dx%d' % (info[1], info[2]))
            self.labelProjectVolDPI.setText('%d,%d' % (info[3], info[4]))
            self.labelProjectVolColor.setText(getColor(info[5]))
            if info[1] == 0 or info[2] == 0:
                self.labelImage.setPixmap(QPixmap(''))
                self.labelImage.setText('非有效图片文件')
            else:
                b = True
                showLabelImage(self.scrollArea, self.labelImage, self.curImage, True)
        else:
            self.labelProjectVolInfo.setText('')
            self.labelProjectVolResolution.setText('')
            self.labelProjectVolDPI.setText('')
            self.labelProjectVolColor.setText('')
            self.labelImage.setText('')
            self.labelImage.setPixmap(QPixmap(''))
        self.pushButtonRotateLeft.setEnabled(b)
        self.pushButtonRotateRight.setEnabled(b)

    def readVolumeFormUI(self):
        # 卷标题-VolumeTitle
        self.curVolumeDict['VolumeTitle'] = self.lineEditVolumeTitle.text()
        # 编制单位-VolumeAuthorUnit
        # self.curVolumeDict['VolumeAuthorUnit'] = self.lineEditVolumeAuthorUnit.text()
        # 分类号 lineEditVolumeClassNo
        # self.curVolumeDict['VolumeClassNo'] = self.lineEditVolumeClassNo.text()
        # 档号 lineEditVolumeFileNo
        self.curVolumeDict['VolumeFileNo'] = self.lineEditVolumeFileNo.text()
        # 卷号 lineEditVolumeNo
        # self.curVolumeDict['VolumeNo'] = self.lineEditVolumeNo.text()
        # 开始-结束时间
        # self.curVolumeDict['VolumeBeginDate'] = dateToStr(self.dateEditVolumeBeginDate)
        # self.curVolumeDict['VolumeEndDate'] = dateToStr(self.dateEditVolumeEndDate)
        # 分类名称-VolumeName
        self.curVolumeDict['VolumeName'] = self.lineEditVolumeName.text()
        # 卷类型-VolumeType
        self.curVolumeDict['VolumeType'] = self.comboBoxVolumeType.currentIndex()
        # 编辑时间-VolumeEditDatetime
        # self.curVolumeDict['VolumeEditDatetime'] = nowDateTimeStr()
        # 编辑人-VolumeEditor
        # self.curVolumeDict['VolumeEditor'] = self.lineEditVolumeEditor.text()

    def isFormFile(self, file):
        name = self.getFormFile(file)
        return '已著录' if os.path.isfile(name) else '未著录'

    def getFormFile(self, file):
        name1 = os.path.dirname(file)
        name2 = os.path.basename(file) + '.frm'
        return pathJoin(name1, name2)

    # 读著录文件
    def readFormFile(self, pname, initData):
        self.fileFormDict[pname] = {}
        name = self.getFormFile(pname)
        if os.path.isfile(name):
            with open(name, 'r', encoding='utf-8') as f:
                data = f.read()
                self.fileFormDict[pname] = json.loads(data)
        if initData != None:
            self.fileFormDict[pname] = self.checkFormDict(self.fileFormDict[pname], initData)
        return self.fileFormDict[pname]

    # 校验数据
    def checkFormDict(self, dictData, initData):
        # 字典深拷贝 2024.4.30
        copyData = copy.deepcopy(initData)
        for k, v in copyData.items():
            if k not in dictData.keys():
                # 添加新键值
                dictData[k] = v
        while True:
            isEqu = True
            for k, v in dictData.items():
                if k not in copyData.keys():
                    # 删除老键值
                    del dictData[k]
                    isEqu = False
                    break
            if isEqu:
                break
        return dictData

    # 写著录文件
    def writeFormFile(self, pname, name):
        setFileNormal(name)
        with open(name, 'w', encoding='utf-8') as f:
            strData = str(self.fileFormDict[pname]).replace('\'', '\"')
            f.write(strData)
            f.close()
        setFileHidden(name)

    def cleanFile(self):
        # 一级著录文件
        flist1 = os.listdir(self.fileLocPath)
        for f in flist1:
            name = pathJoin(self.fileLocPath, f)
            if os.path.isfile(name) and name[-4:] == '.frm':
                if f[:-4] not in flist1:
                    deleteFile(name)
        # 二级著录文件
        for k, v in self.fileDict.items():
            if v[0] != 0:
                continue
            flist2 = os.listdir(k)
            for f in flist2:
                name = pathJoin(k, f)
                if os.path.isfile(name) and name[-4:] == '.frm':
                    if f[:-4] not in flist2:
                        deleteFile(name)

    def writeCache(self):
        name = pathJoin(self.fileLocPath, 'cache.lst')
        setFileNormal(name)
        fd = open(name, 'wt', encoding='utf-8')
        for k, v in self.fileDict.items():
            fd.write('%s|%d\n' % (k, v[0]))
        for dd in self.fileList:
            for k, v in dd.items():
                fd.write('%s|%s\n' % (k, str(v)))
        fd.close()
        setFileHidden(name)

    # 读取著录目录文件
    def cacheReadFile(self, value):
        # 扫描线程
        if value:
            self.clearCache()
        self.fileDict.clear()
        self.fileList.clear()
        self.checkErr = 0
        self.checkErrLog = nowDateStr() + '-err.lst'
        saveLog('', self.fileLocPath, log=self.checkErrLog)
        self.pushButtonReadFile.setEnabled(False)
        self.pushButtonFilePath.setEnabled(False)
        # self.pushButtonClearCache.setEnabled(False)
        self.lineEditCheckTotal.setText('')
        self.textEditCheckResult.clear()
        self.readThread = readFileThread(self.fileLocPath, self.fileExceptList)
        self.readThread.update_item.connect(self.readShow)
        self.readThread.start()

    def readFile(self):
        # 关闭图片窗口
        if self.imageWindow != None:
            self.imageWindow.close()
        # 弹出窗口
        if os.path.isfile(pathJoin(self.fileLocPath, 'cache.lst')):
            self.cacheWin = fileCache(self)
            self.cacheWin.beforeCloseSignal.connect(self.cacheReadFile)
            self.cacheWin.show()
        else:
            self.cacheReadFile(0)

    # 选择目录项
    def readShow(self, flist):
        if len(flist) == 1:
            # 一级目录
            self.fileDict[flist[0]] = [0, 0]
            self.fileFormDict[flist[0]] = {}
            self.readFormFile(flist[0], PROJECT_DICT1)
            if self.timeDiff():
                self.labelState.setText('项目 %d' % (len(self.fileList)))
            return
        if len(flist) == 2:
            # 二级目录
            self.fileDict[flist[0]][1] += 1
            self.fileDict[flist[1]] = [1, len(self.fileList)]
            self.fileList.append({})
            self.fileFormDict[flist[1]] = {}
            self.readFormFile(flist[1], PROJECT_DICT2)
            if self.timeDiff():
                self.labelState.setText('项目 %d' % (len(self.fileList)))
            return
        if len(flist) == 3:
            if isinstance(flist[0], int):
                # err
                self.checkErr += 1
                msg = '%d,%d,[%s],[%s]' % (self.checkErr, flist[0], flist[1], flist[2])
                self.lineEditCheckTotal.setText('出现错误数 %d' % (self.checkErr))
                self.textEditCheckResult.moveCursor(QTextCursor.Start)
                self.textEditCheckResult.insertPlainText(nowTimeStr() + '  ' + msg + '\n')
                saveLog(msg, self.fileLocPath, log=self.checkErrLog)
            else:
                # 文件
                if flist[0] in self.fileDict.keys():
                    index = self.fileDict[flist[0]][1]
                    self.fileList[index][flist[1]] = flist[2]
            return
        # 刷新
        self.pushButtonReadFile.setEnabled(True)
        self.pushButtonFilePath.setEnabled(True)
        # self.pushButtonClearCache.setEnabled(True)
        self.flushTree()

    def getPage(self, pos, pages):
        for p in pages:
            if 'ImageBegin' in list(p.keys()):
                if p['ImageBegin'] == pos:
                    return p['PageBegin']
            if 'ImageEnd' in list(p.keys()):
                if p['ImageEnd'] == pos:
                    return p['PageEnd']
        return 0

    def flushTree(self):
        self.treeWidgetProject.blockSignals(True)
        self.treeWidgetProject.clear()
        self.treeWidgetProject.blockSignals(False)
        # print(self.fileDict)
        # print(self.fileList)
        nums = 0
        n1 = 0
        n2 = 0
        for k, v in self.fileDict.items():
            if v[0] == 0:
                # 序号,一级项目目录,总卷数,著录
                n1 += 1
                n2 = 0
                root1 = QTreeWidgetItem(self.treeWidgetProject)
                root1.setText(0, '%2d ' % (n1))
                root1.setText(1, ' %s  ' % (os.path.basename(k)))
                root1.setText(2, ' %d ' % (v[1]))
                root1.setText(5, ' %s ' % (self.isFormFile(k)))
                continue
            # 序号,二级项目目录,总卷数,著录
            n2 += 1
            root1.setExpanded(True)
            root2 = QTreeWidgetItem(root1)
            root2.setText(0, '%2d.%d ' % (n1, n2))
            root2.setText(1, ' %s  ' % (os.path.basename(k)))
            root2.setText(2, ' %d ' % (len(self.fileList[v[1]])))
            root2.setText(5, ' %s ' % (self.isFormFile(k)))
            # 项目目录,项目编号,总档编号,信息
            vDictPage = self.readFormFile(k, PROJECT_DICT2)['PageList']
            nums += len(self.fileList[v[1]])
            if len(self.fileList[v[1]]) == 0:
                continue
            for i, f in enumerate(self.fileList[v[1]]):
                child = QTreeWidgetItem(root2)
                child.setText(2, ' %d ' % (i + 1))
                child.setText(3, ' %s ' % (os.path.basename(f)))
                # 4-页数
                p = self.getPage(i + 1, vDictPage)
                if p > 0:
                    child.setText(4, ' %d ' % (p))
                child.setText(5, ' %s ' % (isImgOk(self.fileList[v[1]][f])))
        self.labelState.setText('项目-卷：%d-%d' % (len(self.fileList), nums))
        self.labelCurNums.setText('%d' % (n1))

    def selectTreeProject(self, current, previous):
        child = current.parent()
        if child == None:
            # print(" 一级目录 %s" % (current.text(1)))
            current.setExpanded(True)
            self.treeWidgetProject.itemClicked.emit(current, 3)
            return
        root = child.parent()
        if root == None:
            # print(" 二级目录 %s" % (current.text(1)))
            current.setExpanded(True)
            self.treeWidgetProject.itemClicked.emit(current, 3)
            return
        # 选择图片及信息
        # print(" 图片 %s %d" % (current.text(3), current.isSelected()))
        self.treeWidgetProject.itemClicked.emit(current, 3)

    def hoverTreeProject(self, item, col):
        print(" %s" % (item.text(col)))

    def showTreeProject(self, item, col):
        # 选择项目
        child = item.parent()
        if child == None:
            # 选择一级目录
            item.setExpanded(True)
            file = pathJoin(self.fileLocPath, item.text(1).strip())
            # self.lineEditCurInfo.setText(file)
            if self.curTab != 1:
                return
            # 读取配置
            self.curType = 0
            self.curFile1 = file
            self.curItem = item
            self.isModify1 = True
            self.isModify2 = False
            self.curPageTotal = 0
            self.curProjectDict = self.readFormFile(file, PROJECT_DICT1)
            self.curVolumeTotal = self.fileDict[self.curFile1][1]
            self.labelProjectVolTotal.setText('%d' % (self.curVolumeTotal))
            # self.lineEditProjectVolPos.setText('')
            if not self.curProjectDict:
                self.initProjectForm(file)
            self.projectStat()
            self.initProjectFormUI()
            self.setProjectFormUI()
            self.showProjectTotal()
            self.setVolumeFormUI()
            self.setImageFormUI()
            return
        root = child.parent()
        if root == None:
            # 选择二级目录
            item.setExpanded(True)
            self.curFile1 = pathJoin(self.fileLocPath, child.text(1).strip())
            file = pathJoin(self.curFile1, item.text(1).strip())
            # self.lineEditCurInfo.setText(file)
            if self.curTab != 1:
                return
            self.curProjectDict = self.readFormFile(os.path.dirname(file), PROJECT_DICT1)
            if not self.fileFormDict[os.path.dirname(file)]:
                showBox(self, ' 请完成项目著录 ！！！')
                return
            # 读取配置
            self.curType = 1
            self.curFile2 = file
            self.curItem = item
            self.isModify1 = False
            self.isModify2 = True
            self.curVolumeDict = self.readFormFile(file, PROJECT_DICT2)
            self.curVolumeTotal = self.fileDict[self.curFile1][1]
            self.curVolumePos = int(item.text(0).split('.')[1]) - 1
            self.labelProjectVolTotal.setText('%d' % (self.curVolumeTotal))
            # self.lineEditProjectVolPos.setText('%d' % (self.curVolumePos + 1))
            self.curPageTotal = int(item.text(2))
            self.curPagePos = -1
            self.projectStat()
            self.initProjectFormUI()
            self.setProjectFormUI()
            self.showProjectTotal()
            # 案卷著录
            self.initVolumeForm(self.curFile2)
            self.initVolumeFormUI()
            self.setVolumeFormUI()
            self.setImageFormUI()
            return
        # 选择图片及信息
        self.curFile1 = pathJoin(self.fileLocPath, root.text(1).strip())
        self.curFile2 = pathJoin(self.curFile1, child.text(1).strip())
        self.curImage = pathJoin(self.curFile2, item.text(3).strip())
        # self.lineEditCurInfo.setText(self.curImage)
        if self.curTab != 1:
            return
        # self.curFile2 = os.path.dirname(self.curImage)
        # self.curFile1 = os.path.dirname(self.curFile2)
        self.curProjectDict = self.readFormFile(self.curFile1, PROJECT_DICT1)
        self.curPageTotal = int(child.text(2))
        self.curPagePos = -1
        self.curType = 2
        self.isModify1 = False
        self.isModify2 = False
        if self.curProjectDict:
            self.projectStat()
            self.initProjectFormUI()
            self.setProjectFormUI()
            self.showProjectTotal()
        if self.fileFormDict[self.curFile1]:
            self.curVolumeDict = self.readFormFile(self.curFile2, PROJECT_DICT2)
            self.curVolumeTotal = self.fileDict[self.curFile1][1]
            self.curVolumePos = int(child.text(0).split('.')[1]) - 1
            self.labelProjectVolTotal.setText('%d' % (self.curVolumeTotal))
            # self.lineEditProjectVolPos.setText('%d' % (self.curVolumePos + 1))
            # if self.curVolumeDict:
            self.initVolumeFormUI()
            self.setVolumeFormUI()
        self.setImageFormUI()

    # # 导出选择目录
    # def choiceSyncPath(self):
    #     path = QFileDialog.getExistingDirectory(self, " 选择同步档案目录 ", self.syncPath)
    #     if os.path.exists(path):
    #         if path != self.syncPath:
    #             self.syncPath = path
    #             self.config.writeConf('SyncPath', path)
    #             self.lineEditSyncPath.setText(self.syncPath)

    # 导出
    def syncBegin(self):
        # if os.path.isdir(self.syncPath):
        #     l = os.listdir(self.syncPath)
        #     if len(l) > 0:
        #         if not showBoxYes(self, '同步目录非空，是否删除', title='同步提示'):
        #             return
        # 删除导出目录
        self.syncThread = syncThread(self.fileLocPath)
        self.syncThread.update_item.connect(self.syncShow)
        self.syncThread.start()

    def syncShow(self, flist):
        print(flist)

    # 导入选择目录
    # def choiceInputFilePath(self):
    #     path = QFileDialog.getExistingDirectory(self, " 选择导入档案目录 ", self.inputFilePath)
    #     if os.path.exists(path):
    #         if path != self.inputFilePath:
    #             self.inputFilePath = path
    #             self.config.writeConf('InputFilePath', path)
    #             self.lineEditInputFilePath.setText(self.inputFilePath)

    # 导入
    def inputBegin(self):
        # if os.path.isdir(self.inputFilePath):
        #     l = os.listdir(self.inputFilePath)
        #     if len(l) == 0:
        #         showBox(self, '导入目录为空', title='导入提示')
        #         return
        # if os.path.isdir(self.inputFilePath):
        #     if len(self.fileDict) > 0 or len(self.fileList) > 0:
        #         if not showBoxYes(self, '导出目录非空，是否删除', title='导出提示'):
        #             return
        #         showBox(self, ' 当前项目目录有数据，不为空 ！！！')
        #         return
        self.inThread = inputFileThread(self.fileLocPath, self.inputFilePath)
        self.inThread.update_item.connect(self.inShow)
        self.inThread.start()

    def inShow(self, flist):
        print(flist)


class syncThread(QThread):
    update_item = pyqtSignal(list)

    def __init__(self, locPath):
        super().__init__()
        self.locPath = locPath

    def run(self):
        self.update_item.emit([])


class inputFileThread(QThread):
    update_item = pyqtSignal(list)

    def __init__(self, locPath, inPath):
        super().__init__()
        self.locPath = locPath
        self.inPath = inPath

    def run(self):
        self.update_item.emit([])


class readFileThread(QThread):
    update_item = pyqtSignal(list)

    def __init__(self, fileLocPath, fileExceptList):
        super().__init__()
        self.fileLocPath = fileLocPath
        self.fileExceptList = fileExceptList

    def run(self):
        self.fileCache = pathJoin(self.fileLocPath, 'cache.lst')
        n = 0
        if os.path.exists(self.fileCache):
            with open(self.fileCache, 'rt', encoding='utf-8') as fd:
                cacheList = fd.readlines()
                for f in cacheList:
                    s = f.replace('\n', '')
                    sl = s.split('|')
                    if len(sl) != 2:
                        continue
                    n += 1
                    if sl[1] == '0':
                        self.update_item.emit([sl[0]])
                    elif sl[1] == '1':
                        dir = os.path.dirname(sl[0])
                        self.update_item.emit([dir, sl[0]])
                    else:
                        dir = os.path.dirname(sl[0])
                        self.update_item.emit([dir, sl[0], eval(sl[1])])
        if n == 0:
            # 获取目录文件
            dlist1 = natSort(os.listdir(self.fileLocPath))
            for d1 in dlist1:
                dir1 = pathJoin(self.fileLocPath, d1)
                # 第一级
                if not os.path.isdir(dir1):
                    if os.path.splitext(dir1)[1] in RESERVED_EXT:
                        # 保留文件
                        continue
                    if os.path.splitext(dir1)[1] in self.fileExceptList:
                        # 去除文件
                        continue
                    self.update_item.emit([0, '一级目录非法文件', dir1])
                    continue
                self.update_item.emit([dir1])
                # 目录
                dlist2 = natSort(os.listdir(dir1))
                # 第二级
                for d2 in dlist2:
                    dir2 = pathJoin(dir1, d2)
                    if not os.path.isdir(dir2):
                        if os.path.splitext(dir2)[1] in RESERVED_EXT:
                            # 保留文件
                            continue
                        if os.path.splitext(dir2)[1] in self.fileExceptList:
                            # 去除文件
                            continue
                        self.update_item.emit([1, '二级目录非法文件', dir2])
                        continue
                    self.update_item.emit([dir1, dir2])
                    # 文件
                    flist = natSort(os.listdir(dir2))
                    for ff in flist:
                        name = pathJoin(dir2, ff)
                        if not os.path.isfile(name):
                            self.update_item.emit([2, '二级目录非法嵌套目录', name])
                        if os.path.splitext(name)[1] in RESERVED_EXT:
                            # 保留文件
                            continue
                        if os.path.splitext(name)[1] in self.fileExceptList:
                            # 去除文件
                            continue
                        self.update_item.emit([dir2, name, getImgFile(name)])
        self.update_item.emit([])


class checkFileThread(QThread):
    update_item = pyqtSignal(list)

    def __init__(self, curPath, checkList, fileDict, fileList, fileExceptList):
        super().__init__()
        self.curPath = curPath
        self.checkList = checkList
        self.fileDict = fileDict
        self.fileList = fileList
        self.fileExceptList = fileExceptList

    def run(self):
        # 获取目录文件
        dirList = []
        nums = len(self.fileDict) + len(self.fileList)
        n = 0
        name1 = ''
        for k, v in self.fileDict.items():
            name = k[len(self.curPath):]
            if v[0] == 1:
                # 二级文件夹
                dirList.append(k)
            n += 1
            self.update_item.emit([n * 100 / nums])
            err = 0
            # 汉字
            if has_hz(os.path.basename(k)):
                self.update_item.emit([err, name, '文件夹含有汉字'])
                continue
            # 含有特殊字符
            if not has_other(os.path.basename(k)):
                self.update_item.emit([err, name, '文件夹含有特殊字符'])
                continue
            err = 5
            if v[0] == 0 and v[1] == 0:
                self.update_item.emit([err, name, '一级文件夹为空'])
                continue
            if v[0] == 1:
                if len(self.fileList[self.fileDict[k][1]]) == 0:
                    self.update_item.emit([err, name, '二级文件夹为空'])
                    continue
            # 文件夹长度
            err = 1
            if v[0] == 0:
                # 一级
                name1 = os.path.basename(k) + '-'
                sl = os.path.basename(k).split('-')
                if len(sl) != 2:
                    self.update_item.emit([err, name, '一级文件夹结构不符'])
                    continue
                # 判断2段
                if not sl[1].isdigit():
                    self.update_item.emit([err, name, '一级文件夹2段非全数字'])
                # 判断1段
                if not sl[0].isdigit():
                    if not re.match('^[a-zA-Z]+[0-9]+$', sl[0]):
                        self.update_item.emit([err, name, '一级文件夹1段非字母数字'])
            else:
                # 二级
                name2 = os.path.basename(k)
                sl = name2.split('-')
                if len(sl) != 3:
                    self.update_item.emit([err, name, '二级文件夹结构不符'])
                    continue
                if name2[:len(name1)] != name1:
                    self.update_item.emit([err, name, '二级文件夹名称不含一级文件夹'])
                if not sl[2].isdigit():
                    self.update_item.emit([err, name, '二级文件夹3段非全数字'])
        err = 9
        if len(dirList) == 0:
            self.update_item.emit([err, '', '非二级嵌套文件夹'])
        # 二级文件夹下文件
        for dir in dirList:
            n += 1
            self.update_item.emit([n * 100 / nums])
            index = self.fileDict[dir][1]
            flist = self.fileList[index]
            for k in flist:
                # 扩展名
                name = k[len(self.curPath):]
                err = 20
                ext = ['.jpg']
                if os.path.splitext(k)[1] in self.fileExceptList:
                    continue
                if os.path.splitext(k)[1] not in ext:
                    self.update_item.emit([err, name, '文件扩展名错误'])
                # 命名规则
                folder = os.path.basename(dir) + '-'
                err = 30
                if os.path.basename(k)[:len(folder)] != folder:
                    self.update_item.emit([err, name, '文件命名不含二级文件夹错误'])
                err = 31
                sl = os.path.basename(k[:-4]).split('-')
                if len(sl) != 4:
                    self.update_item.emit([err, name, '图像文件名结构错误'])
                    continue
                if not sl[3].isdigit():
                    self.update_item.emit([err, name, '图像文件名4段非全数字'])
                # 文件可读，DPI，颜色
                info = getImgFile(k)
                err = 10
                if info[0] == 0 or info[1] == 0 or info[2] == 0:
                    self.update_item.emit([err, name, '图像文件不可读，已破坏'])
                # DPI
                err = 40
                if info[3] < 300 or info[4] < 300:
                    self.update_item.emit([err, name, '图像文件DPI小于300'])
                # 颜色
                err = 60
                color = []
                if err in self.checkList:
                    color.append('RGB')
                err = 61
                if err in self.checkList:
                    color.append('L')
                if len(color) > 0 and info[5] not in color:
                    self.update_item.emit([60, name, '文件非选择颜色图片'])
        self.update_item.emit([])


if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = fileRun()
    main.show()

    sys.exit(app.exec_())
